const express = require('express');
const router = express.Router();
const Activities = require('../../models/activities/activities');
const { Op } = require('sequelize');

// 创建新活动
router.post('/createActivities', async (req, res) => {
  try {
    const {
      club_id,
      title,
      type,
      description,
      location,
      start_time,
      end_time,
      signup_deadline,
      max_participants,
      points
    } = req.body;

    // 验证必填字段
    if (!club_id || !title || !start_time || !end_time || !signup_deadline) {
      return res.status(400).json({
        success: false,
        message: '缺少必要字段'
      });
    }

    // 验证时间逻辑
    const now = new Date();
    const startTime = new Date(start_time);
    const endTime = new Date(end_time);
    const deadline = new Date(signup_deadline);

    if (startTime <= now) {
      return res.status(400).json({
        success: false,
        message: '活动开始时间必须晚于当前时间'
      });
    }

    if (endTime <= startTime) {
      return res.status(400).json({
        success: false,
        message: '活动结束时间必须晚于开始时间'
      });
    }

    if (deadline >= startTime) {
      return res.status(400).json({
        success: false,
        message: '报名截止时间必须早于活动开始时间'
      });
    }

    // 验证人数限制
    if (max_participants !== undefined && max_participants <= 0) {
      return res.status(400).json({
        success: false,
        message: '最大参与人数必须大于0'
      });
    }

    // 验证积分
    if (points !== undefined && points < 0) {
      return res.status(400).json({
        success: false,
        message: '积分不能为负数'
      });
    }

    // 创建活动
    const activity = await Activities.create({
      club_id,
      title,
      type,
      description,
      location,
      start_time,
      end_time,
      signup_deadline,
      max_participants,
      points: points || 0.00
    });

    res.status(201).json({
      success: true,
      message: '活动创建成功',
      data: activity
    });

  } catch (error) {
    console.error('创建活动失败:', error);
    res.status(500).json({
      success: false,
      message: '创建活动失败',
      error: error.message
    });
  }
});

module.exports = router;
